const db = require('../db');

const PermissionModel = {
    // 创建权限记录
    async createPermission({ role, name, permission, description, status = 1 }) {
        const sql = `
            INSERT INTO permissions (role, name, permission, description, status)
            VALUES (?, ?, ?, ?, ?)
        `;
        const [result] = await db.execute(sql, [
            role,
            name, // 新增
            JSON.stringify(permission),
            description,
            status
        ]);
        return result.insertId;
    },

    // 检查是否存在相同 role（排除指定 ID，用于更新）
    async existsActiveRole(role, excludeId = null) {
        let sql = `SELECT id FROM permissions WHERE role = ? AND status = 1`;
        const params = [role];

        if (excludeId) {
            sql += ' AND id != ?';
            params.push(excludeId);
        }

        const [rows] = await db.execute(sql, params);
        return rows.length > 0;
    },

    // 检查是否存在相同 name（排除指定 ID，用于更新）
    async existsActiveName(name, excludeId = null) {
        let sql = `SELECT id FROM permissions WHERE name = ? AND status = 1`;
        const params = [name];

        if (excludeId) {
            sql += ' AND id != ?';
            params.push(excludeId);
        }

        const [rows] = await db.execute(sql, params);
        return rows.length > 0;
    },

    // 获取所有权限（过滤掉已删除的）
    async getAllPermissions() {
        const sql = `
            SELECT id, role, permission, description, status, created_at, updated_at
            FROM permissions
            WHERE status != 2
        `;
        const [rows] = await db.execute(sql);
        // 将 JSON 字符串解析为数组
        return rows.map(row => ({
            ...row,
            permission: JSON.parse(row.permission)
        }));
    },

    // 根据 ID 获取权限
    async getPermissionById(id) {
        const sql = `SELECT * FROM permissions WHERE id = ? AND status != 2`;
        const [rows] = await db.execute(sql, [id]);
        if (!rows[0]) return null;
        return {
            ...rows[0],
            permission: JSON.parse(rows[0].permission)
        };
    },

    // 更新权限
    async updatePermission(id, updates) {
        const fields = [];
        const values = [];

        for (const key in updates) {
            if (updates[key] !== undefined) {
                if (key === 'permission') {
                    fields.push(`${key} = ?`);
                    values.push(JSON.stringify(updates[key]));
                } else {
                    fields.push(`${key} = ?`);
                    values.push(updates[key]);
                }
            }
        }

        if (fields.length === 0) return false;

        const sql = `
            UPDATE permissions
            SET ${fields.join(', ')}, updated_at = CURRENT_TIMESTAMP
            WHERE id = ?
        `;
        values.push(id);

        const [result] = await db.execute(sql, values);
        return result.affectedRows > 0;
    },

    // 软删除权限（status = 2）
    async deletePermission(id) {
        const sql = `
            UPDATE permissions SET status = 2, updated_at = CURRENT_TIMESTAMP WHERE id = ?
        `;
        const [result] = await db.execute(sql, [id]);
        return result.affectedRows > 0;
    }
};

module.exports = PermissionModel;
